package com.skymxc.wandroidtodo.page.main;

import android.app.Application;

import androidx.annotation.NonNull;

import com.skymxc.wandroidtodo.data.net.NetObserver;
import com.skymxc.wandroidtodo.entity.NetResponse;
import com.skymxc.wandroidtodo.entity.PageResult;
import com.skymxc.wandroidtodo.entity.TODOItem;
import com.skymxc.wandroidtodo.page.base.BasePresenter;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * <p>
 *
 * </p>
 *
 * @author 孟祥超
 * <p>
 * date: 2021/12/2  10:38 下午
 */
public class MainPresenter extends BasePresenter<MainContact.MainView> implements MainContact.IMainPresenter {
    public MainPresenter(Application application) {
        super(application);
    }

    private MainModel mainModel = new MainModel();
    private int page = 1;

    @Override
    public void loadData() {
        mainModel.pageList(page)
                .subscribe(new NetObserver<PageResult>(compositeDisposable, view) {
                    @Override
                    public void onNext(@NonNull PageResult result) {
                        view.loadPageSuccess(result);
                    }

                    @Override
                    public void onComplete() {
                        page++;
                    }
                });
    }

    @Override
    public void refresh() {
        page = 1;
        loadData();
    }

    @Override
    public void updateItemStatus(TODOItem item, boolean isComplete) {
        final int status = isComplete ? 1 : 0;
        view.showProgress("修改中");
        mainModel.updateItemStatus(item, status)
                .subscribe(new NetObserver<TODOItem>(compositeDisposable, view) {
                    @Override
                    public void onNext(@NonNull TODOItem resultItem) {
                        if (resultItem.getStatus() == status) {
                            item.setStatus(resultItem.getStatus());
                            view.updateItemStatusSuccess();
                        } else {
                            view.updateItemStatusFail();
                        }
                    }
                });
    }

    @Override
    public void deleteItem(TODOItem item) {
        view.showProgress("删除中");
        mainModel.deleteItem(item.getId())
                .subscribe(new NetObserver<NetResponse>(compositeDisposable,view) {
                    @Override
                    public void onNext(@NonNull NetResponse response) {
                        if (response.errorCode==0){
                            view.deleteItemSuccess(item);
                        }else{
                            view.showError(response.errorMsg,response.errorCode);
                        }
                    }
                });
    }
}
